package com.ruoyi.project.easyexcel;

import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import org.apache.commons.lang.BooleanUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author huyunqiang
 * @Description
 * @Date 2023/5/10 11:03
 **/
public class EasyExcelRowsTitleHandler implements CellWriteHandler {

    //合并的起始行：key：开始，value；结束
    private Map<Integer, Integer> map;

    //要合并的列
    private List<Integer> cols;

    public EasyExcelRowsTitleHandler() {
    }

    public EasyExcelRowsTitleHandler(Map<Integer, Integer> map, List<Integer> cols) {
        this.map = map;
        this.cols = cols;
    }

    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
                                 Head head, Integer integer, Integer integer1, Boolean aBoolean) {

    }

    @Override
    public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell,
                                Head head, Integer integer, Boolean aBoolean) {

        Object curData = cell.getCellTypeEnum() == CellType.STRING ? cell.getStringCellValue() :
                cell.getNumericCellValue();




    }



    @Override
    public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                       CellData cellData, Cell cell, Head head, Integer integer, Boolean aBoolean) {

        Object curData = cell.getCellTypeEnum() == CellType.STRING ? cell.getStringCellValue() :
                cell.getNumericCellValue();


    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                 List<CellData> list, Cell cell, Head head, Integer integer, Boolean aBoolean) {

        Object curData = cell.getCellTypeEnum() == CellType.STRING ? cell.getStringCellValue() :
                cell.getNumericCellValue();


        //当前行
        int curRowIndex = cell.getRowIndex();
        //当前列
        int curColIndex = cell.getColumnIndex();
        map = new HashMap<>();
        map.put(3,4);  //第三行和第四行合并
        map.put(6,7);  //第六行和第七行合并
        cols = new ArrayList<>();
        cols.add(0);
        Integer endrow = map.get(curRowIndex);

        //编列合并的列，合并行
        if(endrow != null){
            for (Integer col : cols) {
                // CellRangeAddress(起始行,结束行,起始列,结束列)
                writeSheetHolder.getSheet().addMergedRegionUnsafe(new CellRangeAddress(curRowIndex, endrow, col, col));
            }
        }
        //------------------自定义颜色-----------------------根据不同的值设置不同的样式
        if(curData.toString().equals("张三")){
            CellStyle cellStyle = cell.getRow().getSheet().getWorkbook().createCellStyle();
            cellStyle.setBorderBottom(BorderStyle.THIN);
            cellStyle.setBorderLeft(BorderStyle.THIN);
            cellStyle.setBorderRight(BorderStyle.THIN);
            cellStyle.setBorderTop(BorderStyle.NONE);

            Font font = cell.getRow().getSheet().getWorkbook().createFont();
            font.setColor(IndexedColors.RED.index);
            // 字体
            font.setFontName("宋体");
            // 字体大小
            font.setFontHeightInPoints((short) 14);
            // 设置加粗
            font.setBold(false);

            cellStyle.setFont(font);
            cell.setCellStyle(cellStyle);
        }

    }

    /**
     * 相同的值合并
     * @param writeSheetHolder
     * @param cell
     * @param curRowIndex
     * @param curColIndex
     * @return
     */
    private Cell mergeWithPrevRow(WriteSheetHolder writeSheetHolder, Cell cell, int curRowIndex, int curColIndex) {

        //获取当前行的当前列的数据和上一行的当前列列数据，通过上一行数据是否相同进行合并
        Object curData = cell.getCellTypeEnum() == CellType.STRING ? cell.getStringCellValue() :
                cell.getNumericCellValue();
        Row preRow = cell.getSheet().getRow(curRowIndex - 1);
        if (preRow == null) {
            // 当获取不到上一行数据时，使用缓存sheet中数据
            preRow = writeSheetHolder.getCachedSheet().getRow(curRowIndex - 1);
        }
        Cell preCell=preRow.getCell(curColIndex);
        Object preData = preCell.getCellTypeEnum() == CellType.STRING ? preCell.getStringCellValue() :
                preCell.getNumericCellValue();

        // 比较当前行的第一列的单元格与上一行是否相同，相同合并当前单元格与上一行

        if (curData.equals(preData)) {
            Sheet sheet = writeSheetHolder.getSheet();

            List<CellRangeAddress> mergeRegions = sheet.getMergedRegions();


            boolean isMerged = false;
            for (int i = 0; i < mergeRegions.size() && !isMerged; i++) {
                CellRangeAddress cellRangeAddr = mergeRegions.get(i);

                // 若上一个单元格已经被合并，则先移出原有的合并单元，再重新添加合并单元
                if (cellRangeAddr.isInRange(curRowIndex - 1, curColIndex)) {
                    sheet.removeMergedRegion(i);
                    cellRangeAddr.setLastRow(curRowIndex);
                    sheet.addMergedRegion(cellRangeAddr);
                    isMerged = true;
                }
            }
            // 若上一个单元格未被合并，则新增合并单元
            if (!isMerged) {
                CellRangeAddress cellRangeAddress = new CellRangeAddress(curRowIndex - 1, curRowIndex, curColIndex,
                        curColIndex);

                sheet.addMergedRegion(cellRangeAddress);

            }

        }
            return cell;
    }

}
